package com.gooluke.redirect.resolver;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
import com.gooluke.redirect.repository.ShortUrlRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class TieredCacheUrlResolver implements UrlResolver {

    // 1. 本地缓存（Caffeine）
    private final Cache<String, String> localCache = Caffeine.newBuilder()
            .maximumSize(10_000)
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .build();

    // 2. Redis缓存
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 3. 数据库回源
    @Autowired
    private ShortUrlRepository repository;

    @Override
    public String resolve(String shortCode) {
        // 先查本地缓存
        return localCache.get(shortCode, code -> {
                    // 再查Redis
                    String originalUrl = redisTemplate.opsForValue().get("short:url:" + code);
                    if (originalUrl != null) {
                        return originalUrl;
                    }
                    // 最后查数据库
                    return repository.findOriginalUrl(code).orElse(null);
                }
        );
    }
}